<template>
    <ElDialog v-model="dialogVisible" width="600px" :title="title">
        <el-form ref="formRef" :model="validateForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="资金方名称" prop="fundName" :rules="{ required: true, message: '请输入资金方名称' }">
                <el-input v-model="validateForm.fundName" type="text" placeholder="请输入资金方名称"/>
            </el-form-item>
            <el-form-item label="资金方简称" prop="fundShorterForm" :rules="{ required: true, message: '请输入资金方简称' }">
                <el-input v-model="validateForm.fundShorterForm" type="text" placeholder="请输入资金方简称"/>
            </el-form-item>
            <el-form-item label="排序" prop="fundSort" :rules="[{ required: true, message: '请输入排序' },{ type: 'number', message: '排序必须为数字' },]">
                <el-input v-model.number="validateForm.fundSort" type="text" placeholder="请输入排序"/>
            </el-form-item>
            <el-form-item label="机构代码" prop="creditCode" :rules="{ required: true, message: '请输入机构代码' }">
                <el-input v-model="validateForm.creditCode" type="text" placeholder="请输入机构代码"/>
            </el-form-item>
            <el-form-item label="分类" prop="fundType" :rules="{ required: true, message: '请输入分类' }">
                <el-select v-model="validateForm.fundType" placeholder="请选择分类"  style="width: 100%;">
                    <el-option v-for="item in funderType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="服务区域" prop="serviceArea" :rules="{ required: true, message: '请输入服务区域' }">
                <ElCascader v-model="validateForm.serviceArea" :options="[{label: '全国',value: '全国'}, ...cascaderAddress()]" :props="propsCascader" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="状态" prop="fundStatus" :rules="{ required: true, message: '请选择状态' }">
                <el-radio-group v-model="validateForm.fundStatus" class="ml-4">
                    <el-radio v-for="item in funderStatus" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="机构logo" prop="fundLogUrl">
                <el-upload
                    v-model:file-list="fileList"
                    action="#"
                    :auto-upload="false" 
                    :limit="1"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-exceed="fileExceed"
                    :on-change="handleChange"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="备注" prop="fundNote">
                <el-input v-model="validateForm.fundNote" :rows="2" type="textarea" placeholder="请输入备注"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <ElButton @click="dialogVisible = false">取消</ElButton>
                <ElButton type="primary" @click="submitForm(formRef)">确定</ElButton>
            </span>
        </template>
    </ElDialog>
    <ElDialog v-model="dialogImg" width="800px"><el-image style="width: 100%" :src="dialogImageUrl" fit="cover" /></ElDialog>
</template>
<script setup>
import {ElDialog, ElButton, ElForm, ElFormItem, ElInput, ElRadioGroup, ElRadio, ElSelect, ElOption, ElUpload, ElIcon, ElCascader, ElMessage, ElImage, ElLoading } from 'element-plus'
import { computed, ref, reactive, onMounted } from 'vue';
import {funderType, funderStatus} from "@/utils/enum.js"
import {cascaderAddress} from '@/utils/addressData';
import {Plus} from '@element-plus/icons-vue'
import {setFund} from '@/server/manage/product.js'
import {uploadFile} from "@/server/common/files.js"
const props = defineProps(['modelValue', 'type', 'info'])
const emit = defineEmits(['update:modelValue', "callback"])
const formRef = ref()
const fileList = ref([])
const dialogImageUrl = ref()
const dialogImg = ref(false)
const validateForm = reactive({
    "fundName": "", //资金方名
    "fundShorterForm": "", //资金方简称
    "creditCode": "", //机构代码
    "fundType": "", //分类
    "serviceArea": "", //服务区域
    "fundStatus": "", //状态
    "fundNote": "", //备注
    "fundLogUrl": "",
    "fundSort": "" // 排序
})
const dialogVisible = computed({
    set:(val) => {
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue
    }
})
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[props.type]
})
// 地址选择配置
const propsCascader = {
    multiple: true,
    checkStrictly: true
}
console.log(cascaderAddress());
// 上传文件
const uploadFun = async() => {
    return new Promise((resolve, rejects) => {
        if(fileList.value[0]?.type === 'string') {resolve(fileList.value[0]?.url)}
        else if(fileList.value[0]){
            let formData = new FormData()
            formData.append("file", fileList.value[0].raw)
            uploadFile(formData).then(res => {
                resolve(res.fundLogUrl)
            }).catch(msg => {
                rejects(msg)
            })
        }else {
          resolve("")
        }
    })
}
// 提交
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate( async(valid) => {
    if (valid) {
        const loadingInstance = ElLoading.service({lock: true,text: '提交中',background: 'rgba(0, 0, 0, 0.3)',})
        let url = await uploadFun()
        let obj = {add: 'save',edit: 'update' }
        let params = JSON.parse(JSON.stringify(validateForm))
        params.serviceArea = validateForm.serviceArea.join('; ').toString()
        params.serviceArea = params.serviceArea.replace(/,/g, "/")
        params.fundLogUrl = url
        setFund(params, obj[props.type]).then(res => {
            dialogVisible.value = false
            loadingInstance.close()
            emit('callback')
            ElMessage({ message: "操作成功！", type: 'success'})
        }).catch(msg => {
            loadingInstance.close()
        })
    } else {
      return false
    }
  })
}
// 删除附件
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
// 查看图片
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogImg.value = true
}
// 超出文件个数限制提示
const fileExceed = () => {
    ElMessage.error('只能上传一个文件！')
}
// 图片发上变化
const handleChange = (res) => {
    let check = beforeAvatarUpload(res.raw)
    if(!check) fileList.value = []
}
// 文件检测
const beforeAvatarUpload = (rawFile) => {
    console.log("rawFile", rawFile);
  if (rawFile.type !== 'image/png') {
    ElMessage.error('请上传png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 60) {
    ElMessage.error('文件不能大于60MB!')
    return false
  }
  return true
}
// 获取详情
const getDetail = () => {
    for(let key in validateForm) {
        if(props.info[key]) validateForm[key] = props.info[key]
    }
    validateForm.serviceArea = validateForm.serviceArea?.split('; ');
    validateForm.serviceArea = validateForm.serviceArea.map(item => {
        return item.split('/')
    })
    if(props.info.fundLogUrl) {fileList.value[0] = {url: props.info.fundLogUrl, type: "string"}}
    validateForm.id = props.info.id
}
onMounted(() => {
    if(props.type === 'edit') {getDetail()}
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
.delete-icon{
    position: absolute;
    right: 0;
    top: 0;
    background: rgba(0,0,0,.1);
    width: 30px;
    height: 30px;
    border-radius: 50%;
}
</style>